{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2023 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# cumulative_variable_profile_sample_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/sat/cumulative_variable_profile_sample_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/ortools/sat/samples/cumulative_variable_profile_sample_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "Solve a simple scheduling problem with a variable work load."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import io\n",
    "\n",
    "import pandas as pd\n",
    "\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "\n",
    "def create_data_model() -> tuple[pd.DataFrame, pd.DataFrame]:\n",
    "    \"\"\"Creates the two dataframes that describes the model.\"\"\"\n",
    "\n",
    "    capacity_str: str = \"\"\"\n",
    "  start_hour  capacity\n",
    "     0            0\n",
    "     2            0\n",
    "     4            1\n",
    "     6            3\n",
    "     8            6\n",
    "    10           12\n",
    "    12            8\n",
    "    14           12\n",
    "    16           10\n",
    "    18            4\n",
    "    20            2\n",
    "    22            0\n",
    "  \"\"\"\n",
    "\n",
    "    tasks_str: str = \"\"\"\n",
    "  name  duration load  priority\n",
    "   t1      60      3      2\n",
    "   t2     180      2      1\n",
    "   t3     240      5      3\n",
    "   t4      90      4      2\n",
    "   t5     120      3      1\n",
    "   t6     300      3      3\n",
    "   t7     120      1      2\n",
    "   t8     100      5      2\n",
    "   t9     110      2      1\n",
    "   t10    300      5      3\n",
    "   t11     90      4      2\n",
    "   t12    120      3      1\n",
    "   t13    250      3      3\n",
    "   t14    120      1      2\n",
    "   t15     40      5      3\n",
    "   t16     70      4      2\n",
    "   t17     90      8      1\n",
    "   t18     40      3      3\n",
    "   t19    120      5      2\n",
    "   t20     60      3      2\n",
    "   t21    180      2      1\n",
    "   t22    240      5      3\n",
    "   t23     90      4      2\n",
    "   t24    120      3      1\n",
    "   t25    300      3      3\n",
    "   t26    120      1      2\n",
    "   t27    100      5      2\n",
    "   t28    110      2      1\n",
    "   t29    300      5      3\n",
    "   t30     90      4      2\n",
    "  \"\"\"\n",
    "\n",
    "    capacity_df = pd.read_table(io.StringIO(capacity_str), sep=r\"\\s+\")\n",
    "    tasks_df = pd.read_table(io.StringIO(tasks_str), index_col=0, sep=r\"\\s+\")\n",
    "    return capacity_df, tasks_df\n",
    "\n",
    "\n",
    "def main():\n",
    "    \"\"\"Create the model and solves it.\"\"\"\n",
    "    capacity_df, tasks_df = create_data_model()\n",
    "\n",
    "    # Create the model.\n",
    "    model = cp_model.CpModel()\n",
    "\n",
    "    # Get the max capacity from the capacity dataframe.\n",
    "    max_capacity = capacity_df.capacity.max()\n",
    "    print(f\"Max capacity = {max_capacity}\")\n",
    "    print(f\"#tasks = {len(tasks_df)}\")\n",
    "\n",
    "    minutes_per_period: int = 120\n",
    "    horizon: int = 24 * 60\n",
    "\n",
    "    # Variables\n",
    "    starts = model.NewIntVarSeries(\n",
    "        name=\"starts\", lower_bounds=0, upper_bounds=horizon, index=tasks_df.index\n",
    "    )\n",
    "    performed = model.NewBoolVarSeries(name=\"performed\", index=tasks_df.index)\n",
    "\n",
    "    intervals = model.NewOptionalFixedSizeIntervalVarSeries(\n",
    "        name=\"intervals\",\n",
    "        index=tasks_df.index,\n",
    "        starts=starts,\n",
    "        sizes=tasks_df.duration,\n",
    "        are_present=performed,\n",
    "    )\n",
    "\n",
    "    # Set up the profile. We use fixed (intervals, demands) to fill in the space\n",
    "    # between the actual load profile and the max capacity.\n",
    "    time_period_intervals = model.NewFixedSizeIntervalVarSeries(\n",
    "        name=\"time_period_intervals\",\n",
    "        index=capacity_df.index,\n",
    "        starts=capacity_df.start_hour * minutes_per_period,\n",
    "        sizes=minutes_per_period,\n",
    "    )\n",
    "    time_period_heights = max_capacity - capacity_df.capacity\n",
    "\n",
    "    # Cumulative constraint.\n",
    "    model.AddCumulative(\n",
    "        intervals.to_list() + time_period_intervals.to_list(),\n",
    "        tasks_df.load.to_list() + time_period_heights.to_list(),\n",
    "        max_capacity,\n",
    "    )\n",
    "\n",
    "    # Objective: maximize the value of performed intervals.\n",
    "    # 1 is the max priority.\n",
    "    max_priority = max(tasks_df.priority)\n",
    "    model.Maximize(sum(performed * (max_priority + 1 - tasks_df.priority)))\n",
    "\n",
    "    # Create the solver and solve the model.\n",
    "    solver = cp_model.CpSolver()\n",
    "    solver.parameters.log_search_progress = True\n",
    "    solver.parameters.num_workers = 8\n",
    "    solver.parameters.max_time_in_seconds = 30.0\n",
    "    status = solver.Solve(model)\n",
    "\n",
    "    if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:\n",
    "        start_values = solver.Values(starts)\n",
    "        performed_values = solver.BooleanValues(performed)\n",
    "        for task in tasks_df.index:\n",
    "            if performed_values[task]:\n",
    "                print(f\"task {task} starts at {start_values[task]}\")\n",
    "            else:\n",
    "                print(f\"task {task} is not performed\")\n",
    "    elif status == cp_model.INFEASIBLE:\n",
    "        print(\"No solution found\")\n",
    "    else:\n",
    "        print(\"Something is wrong, check the status and the log of the solve\")\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}
